package com.yixun.qfbao.controller.agency.weapp;

import com.yixun.common.page.Page;
import com.yixun.qfbao.annotations.ForbidRepeatClick;
import com.yixun.qfbao.api.service.*;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.request.BaseRequest;
import com.yixun.qfbao.request.GenericIdListRequest;
import com.yixun.qfbao.request.GenericIdRequest;
import com.yixun.qfbao.request.PageRequest;
import com.yixun.qfbao.request.customerpremises.GetReportModelReqDto;
import com.yixun.qfbao.response.BaseResponse;
import com.yixun.qfbao.response.customerpremises.ReportConvert;
import com.yixun.qfbao.response.customerpremises.ReportDetailResDto;
import com.yixun.qfbao.response.customerpremises.ReportModel;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesAffixDto;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @program: channel-parent
 *
 * @description: 报备业务相关接口
 *
 * @author: Seven.wang
 *
 * @create: 2020-07-31 11:22
 **/
@Controller
@ResponseBody
@RequestMapping("/agency/weapp/cp")
@Api(tags = {"分销小程序-报备"})
public class CustomerPremisesController {

    private static Logger logger= LoggerFactory.getLogger(CustomerPremisesController.class);

    @Autowired
    private CPService cpService;
    @Autowired
    @Lazy
    private CPReportService cpReportService;
    @Autowired
    private CPFollowUPService cpFollowUPService;
    @Autowired
    private ReportModelApiService reportModelApiService;
    @Autowired
    private AffixService affixService;
    @Autowired
    private CustomerPremisesService customerPremisesService;
    @Autowired
    private ThirdPartyApiService thirdPartyApiService;
    
    @Autowired
    private PremisesRecommenderService premisesRecommenderService;

    @Autowired
    private WxAccessTokenCacheUtils wxAccessTokenCacheUtils;

    @ApiOperation(notes = "获取报备列表分页", value="获取报备分页")
    @PostMapping("/getCPPage")
    public BaseResponse<Page<CustomerPremisesDto>> getCPPage(@RequestBody PageRequest<GetCustomerPremisesPageReqDto> request){
        BaseResponse<Page<CustomerPremisesDto>> res = new BaseResponse<>();
        GetCustomerPremisesPageReqDto reqDto = buildCPPageReqDto(request);

        String userId = request.getUserId();
        if(StringUtils.isBlank(userId)) {
            res.setCode(ResultEnum.USER_IS_NULL.getNo());
            res.setMsg(ResultEnum.USER_IS_NULL.getDes());
            return res;
        }
        reqDto.setUserId(userId);
        reqDto.setLoginType(request.getLoginType());
        String companyUuid = request.getCompanyUuid();
        if(StringUtils.isBlank(companyUuid)) {
            res.setCode(ResultEnum.COMPANY_IS_NULL.getNo());
            res.setMsg(ResultEnum.COMPANY_IS_NULL.getDes());
            return res;
        }
        reqDto.setCompanyUuid(companyUuid);
        Page<CustomerPremisesDto> cpPage = cpService.getWeappCPPage(reqDto);
        res.setData(cpPage);
        res.setCode(ResultEnum.SUCCESS.getNo());
        res.setMsg(ResultEnum.SUCCESS.getDes());
        return res;
    }

    private GetCustomerPremisesPageReqDto buildCPPageReqDto(PageRequest<GetCustomerPremisesPageReqDto> request) {
        GetCustomerPremisesPageReqDto getPremisesReqDto = request.getSearchDTO();
        GetCustomerPremisesPageReqDto reqDto = new GetCustomerPremisesPageReqDto();
        if(getPremisesReqDto != null) {
            BeanUtils.copyProperties(getPremisesReqDto, reqDto);
        }
        reqDto.setUserId(request.getUserId());
        reqDto.setLoginType(request.getLoginType());
        reqDto.setCompanyUuid(request.getCompanyUuid());
        reqDto.setPageNo(request.getPageDTO().getPageNum());
        reqDto.setPageSize(request.getPageDTO().getPageSize());
        return reqDto;
    }

    @ApiOperation(notes = "获取报备详情", value="获取报备详情")
    @PostMapping("/getCPDetail")
    public BaseResponse<ReportDetailResDto> getCPDetail(@RequestBody BaseRequest<GetCPDetailReqDto> request){
        BaseResponse<ReportDetailResDto> response = new BaseResponse<>();
        GetCPDetailReqDto reqDto = buildGetCPDetailReqDto(request);
        if(StringUtils.isBlank(reqDto.getId())){
            return response;
        }
        GetCPDetailResDto cpDetail = cpReportService.getCPDetail(reqDto);

        List<CustomerPremisesAffixDto> affixDtoList = affixService.listAffixByAffixType(Long.valueOf(reqDto.getId()), null);

        CustomerPremises customerPremises = new CustomerPremises();
        BeanUtils.copyProperties(cpDetail.getCpDto(), customerPremises);
        Map<String, String> statusMap = customerPremisesService.getCusStatus(customerPremises);

        ReportDetailResDto resDto = ReportConvert.convertDetail2ResDto(cpDetail, affixDtoList, statusMap);

        response.setData(resDto);
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        return response;
    }

    private GetCPDetailReqDto buildGetCPDetailReqDto(BaseRequest<GetCPDetailReqDto> request) {
        GetCPDetailReqDto getPremisesReqDto = request.getData();
        GetCPDetailReqDto reqDto = new GetCPDetailReqDto();
        if(getPremisesReqDto != null) {
            BeanUtils.copyProperties(getPremisesReqDto, reqDto);
        }
        reqDto.setUserId(request.getUserId());
        reqDto.setLoginType(request.getLoginType());
        reqDto.setCompanyUuid(request.getCompanyUuid());
        return reqDto;
    }

    @ApiOperation(notes = "获取报备跟进列表", value="获取报备跟进列表")
    @PostMapping("/getCPFollowList")
    public BaseResponse<GetCPFollowListResDto> getCPFollowList(@RequestBody BaseRequest<GetCPFollowListReqDto> request){
        BaseResponse<GetCPFollowListResDto> response = new BaseResponse<>();
        GetCPFollowListReqDto reqDto = request.getData();
        GetCPFollowListResDto resDto = new GetCPFollowListResDto();
        try {
            resDto = cpFollowUPService.getCPFollowList(reqDto);
        } catch (Exception e) {
            logger.error("getCPFollowList error: {}", e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("系统异常");
        }
        response.setData(resDto);
        response.setCode(resDto.getResult());
        response.setMsg(resDto.getResultMsg());
        return response;
    }

    @ApiOperation(notes = "报备跟进新增", value="报备跟进新增")
    @PostMapping("/addFollow")
    public BaseResponse<AddFollowResDto> addFollow(@RequestBody BaseRequest<AddFollowReqDto> request){
        BaseResponse<AddFollowResDto> response = new BaseResponse<>();
        AddFollowReqDto reqDto = request.getData();
        AddFollowResDto resDto = new AddFollowResDto();
        try {
            String assistantAccessToken = wxAccessTokenCacheUtils.getAccessToken(request.getCompanyUuid(), SystemIdEnum.ASSISTANT.getCode(), null);
            reqDto.setAssistantAccessToken(assistantAccessToken);

            reqDto.setDomain(request.getDomain());
            reqDto.setCompanyUuid(request.getCompanyUuid());
            reqDto.setLoginType(request.getLoginType());
            reqDto.setUserId(request.getUserId());
            reqDto.setOpenId(request.getOpenId());
            resDto = cpFollowUPService.addFollow(reqDto);
        } catch (Exception e) {
            logger.error("addFollow error: {}", e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("系统异常");
        }
        response.setData(resDto);
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        return response;
    }

    @ApiOperation(notes = "选择楼盘批量报备获取报备模板", value="选择楼盘批量报备获取报备模板")
    @PostMapping("/batchReportModelList")
    public BaseResponse<BatchReportModelListResDto> batchReportModelList(@RequestBody BaseRequest<BatchReportModelListReqDto> request){
        BaseResponse<BatchReportModelListResDto> response = new BaseResponse<>();
        BatchReportModelListReqDto reqDto = request.getData();
        BatchReportModelListResDto resDto = new BatchReportModelListResDto();
        try {
            resDto = reportModelApiService.batchReportModelList(reqDto);
        } catch (Exception e) {
            logger.error("batchReportModelList error: {}", e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("系统异常");
        }
        response.setData(resDto);
        response.setCode(resDto.getResult());
        response.setMsg(resDto.getResultMsg());
        return response;
    }

    @ApiOperation(notes = "批量报备校验", value="批量报备校验")
    @PostMapping("/checkBatchReport")
    public BaseResponse<BatchReportResDto> checkBatchReport(@RequestBody BaseRequest<BatchReportReqDto> request){
        BaseResponse<BatchReportResDto> response = new BaseResponse<>();
        BatchReportReqDto reqDto = request.getData();
        BatchReportResDto resDto = new BatchReportResDto();
        try {
            resDto = cpReportService.checkBatchReport(reqDto);
        } catch (Exception e) {
            logger.error("checkBatchReport error: {}", e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("系统异常");
        }
        response.setData(resDto);
        response.setCode(resDto.getResult());
        response.setMsg(resDto.getResultMsg());
        return response;
    }

    @ForbidRepeatClick
    @ApiOperation(notes = "批量报备", value="批量报备")
    @PostMapping("/addBatchReport")
    public BaseResponse<AddBatchReportResDto> addBatchReport(@RequestBody BaseRequest<BatchReportReqDto> request){
        BaseResponse<AddBatchReportResDto> response = new BaseResponse<>();
        BatchReportReqDto reqDto = request.getData();
        AddBatchReportResDto resDto = new AddBatchReportResDto();
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        try {
            //获取案场助手的微信accessToken
            String assistantAccessToken = wxAccessTokenCacheUtils.getAccessToken(request.getCompanyUuid(), SystemIdEnum.ASSISTANT.getCode(), request.getDomain());
            reqDto.setUserId(request.getUserId());
            reqDto.setCompanyUuid(request.getCompanyUuid());
            resDto = cpReportService.addBatchReport(reqDto, assistantAccessToken);
        } catch (Exception e) {
            logger.error("addBatchReport error: {}", e);
            response.setCode(ResultEnum.FAIL.getNo());
            response.setMsg(ResultEnum.FAIL.getDes());
        }
        response.setData(resDto);
        return response;
    }

    @ApiOperation(notes = "报备模板", value="报备模板")
    @PostMapping("/getReportModel")
    public BaseResponse<ReportModel> getReportModel(@RequestBody BaseRequest<GetReportModelReqDto> request){
        BaseResponse<ReportModel> response = new BaseResponse<>();
        ReportModel reportModel = new ReportModel();
        try {
            // 复用了公众号的接口及返回值
            // 并重新将公众号接口先关对象的内容复制给了小程序的接口对象
            GetReportModelReqDto requestDto = request.getData();

            GetReportModelInfoListReqDto reqDto = new GetReportModelInfoListReqDto();
            BeanUtils.copyProperties(requestDto, reqDto);
            reqDto.setUserId(request.getUserId());
            reqDto.setLoginType(request.getLoginType());
            GetReportModelInfoListResDto resDto = reportModelApiService.getReportModeInfoList(reqDto);
            reportModel.setReportModelInfoList(resDto.getReportModelInfoList());
            reportModel.setRepotModelDetail(resDto.getRepotModelDetail());
        } catch (Exception e) {
            logger.error("addBatchReport error: {}", e);
            response.setCode(ResultEnum.FAIL.getNo());
            response.setMsg(ResultEnum.FAIL.getDes());
        }
        response.setData(reportModel);
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        return response;
    }

    @ApiOperation(notes = "创建二维码", value="创建二维码")
    @PostMapping("/createQRCode")
    public BaseResponse<String> createQRCode(@RequestBody BaseRequest<GenericIdRequest> request){
        BaseResponse<String> response = new BaseResponse<>();
        String qrCode = "";
        try {
            CreateQRCodeReqDto reqDto = new CreateQRCodeReqDto();
            reqDto.setContent(String.valueOf(request.getData().getId()));
            CreateQRCodeResDto resDto = thirdPartyApiService.createQRCode(reqDto);
            if(StringUtils.isNotBlank(resDto.getQrCode())){
                qrCode = resDto.getQrCode();
                qrCode =  qrCode.replaceAll("\n","");
                qrCode = qrCode.replaceAll("\r","");
            }
        } catch (Exception e) {
            logger.error("addBatchReport error: {}", e);
            response.setCode(ResultEnum.FAIL.getNo());
            response.setMsg(ResultEnum.FAIL.getDes());
        }
        response.setData(qrCode);
        response.setCode(ResultEnum.SUCCESS.getNo());
        response.setMsg(ResultEnum.SUCCESS.getDes());
        return response;
    }
    
    @ApiOperation(notes = "获取报备推荐人列表", value="获取报备推荐人列表")
    @PostMapping("/getRecommendList")
    public BaseResponse<GetRecommendListResDto> getRecommendList(@RequestBody BaseRequest<GenericIdListRequest> request){
        BaseResponse<GetRecommendListResDto> response = new BaseResponse<>();
        List<Long> premisesIds = request.getData().getIds();
        if(CollectionUtils.isEmpty(premisesIds)){
        	response.setCode(ResultEnum.FAIL.getNo());
        	response.setMsg("楼盘ID不能为空!");
            return response;
        }
        Map<String, List<PremisesRecommenderDto>> dtoMap = 
        		premisesRecommenderService.selectListByPremisesIds(premisesIds);
        GetRecommendListResDto getRecommendListResDto = new GetRecommendListResDto();
        getRecommendListResDto.setRecommendListMap(dtoMap);;
        response.setData(getRecommendListResDto);
        response.setCode(ResultEnum.SUCCESS.getNo());
        return response;
    }

}
